import Menu from "ant-design-vue/es/menu";
import Icon from "ant-design-vue/es/icon";
import { getI18nKey, slashToHump } from "@/utils/routerUtil";
import IconFonts from "@/components/TopVUI/font/iconFont-offLine.vue";
import { flatTreeData } from "@/utils/util";
import { projectId } from "@/blackHole/config";
import { mapGetters } from "vuex";

const { Item, SubMenu } = Menu;
const resolvePath = (path, params = {}) => {
  let _path = path;
  Object.entries(params).forEach(([key, value]) => {
    _path = _path.replace(new RegExp(`:${key}`, "g"), value);
  });
  return _path;
};

const toRoutesMap = (routes) => {
  const map = {};
  routes.forEach((route) => {
    map[route.fullPath] = route;
    if (route.children && route.children.length > 0) {
      const childrenMap = toRoutesMap(route.children);
      Object.assign(map, childrenMap);
    }
  });
  return map;
};

export default {
  name: "SMenu",
  // i18n: require("../../router/i18n1"),
  props: {
    menu: {
      type: Array,
      required: true,
    },
    theme: {
      type: String,
      required: false,
      default: "dark",
    },
    mode: {
      type: String,
      required: false,
      default: "inline",
    },
    collapsed: {
      type: Boolean,
      required: false,
      default: false,
    },
    i18n: Object,
  },
  data() {
    return {
      sOpenKeys: [],
      selectedKeys: [],
      cachedOpenKeys: [],
    };
  },
  computed: {
    ...mapGetters(["currentProjectCode"]),
    menuTheme() {
      if (
        this.theme == "mix" ||
        this.theme == "light" ||
        this.theme == "honeywell"
      ) {
        return "light";
      } else if (this.theme == "dark") {
        return "dark";
      }
    },
    rootSubmenuKeys: (vm) => {
      const keys = [];
      vm.menu.forEach((item) => keys.push(item.path));
      return keys;
    },
  },
  created() {
    this.updateMenu();
    // 自定义国际化配置
    if (this.i18n && this.i18n.messages) {
      const messages = this.i18n.messages;
      Object.keys(messages).forEach((key) => {
        this.$i18n.mergeLocaleMessage(key, messages[key]);
      });
    }
  },
  watch: {
    collapsed(val) {
      if (val) {
        this.cachedOpenKeys = this.sOpenKeys;
        this.sOpenKeys = [];
      } else {
        this.sOpenKeys = this.cachedOpenKeys;
      }
    },
    $route: function() {
      this.updateMenu();
    },
    i18n(val) {
      if (val && val.messages) {
        const messages = this.i18n.messages;
        Object.keys(messages).forEach((key) => {
          this.$i18n.mergeLocaleMessage(key, messages[key]);
        });
      }
    },
  },
  // <icon-fonts : icon = "'icon-' + options.iconFont" class = "card-title-icon": style = "{ color: options.iconFontColor }" / >
  methods: {
    renderIcon: function(h, icon) {
      if (icon === "none" || icon === undefined || icon === null) {
        return null;
      }
      const props = {};
      typeof icon === "object"
        ? (props.icon = "icon-" + icon)
        : (props.icon = "icon-" + icon);
      props.type = "small";
      return h(IconFonts, {
        props: {
          ...props,
        },
      });
    },
    renderMenuItem: function(h, menu, pIndex, index) {
      const target = menu.meta.target || null;
      return h(
        Item,
        {
          //   key: menu.path ? menu.path : "item_" + pIndex + "_" + index,
          key: menu.menuCode,
        },
        [
          h(
            menu.meta.autoRouter ? "div" : "router-link",
            {
              on: {
                click: (e) => this.autoRouterClick(menu),
              },
              attrs: {
                to: {
                  //   name: menu.name,
                  path: menu.menuUrl,
                  query: menu.meta.query,
                },
                href: menu.meta.link,
                title: this.$te(slashToHump(menu.fullPath))
                  ? this.$t(slashToHump(menu.fullPath))
                  : menu.meta.title,
                target: target,
              },
            },
            [
              this.renderIcon(h, menu.meta.icon),
              // h('span', [menu.meta.title])
              // h('span', this.translation(getI18nKey(menu.fullPath))?this.$t(getI18nKey(menu.fullPath)):[menu.meta.title])
              h(
                "span",
                {
                  class: menu.meta.autoRouter ? "span" : "",
                },
                this.$te(slashToHump(menu.fullPath))
                  ? this.$t(slashToHump(menu.fullPath))
                  : [menu.meta.title]
              ),
            ]
          ),
        ]
      );
    },
    renderSubMenu: function(h, menu, pIndex, index) {
      const this2_ = this;
      // const subItem = [h('span', { slot: 'title' }, [this.renderIcon(h, menu.meta.icon), h('span', [menu.meta.title])])]
      const subItem = [
        h(
          "span",
          {
            slot: "title",
            attrs: {
              title: this.$te(slashToHump(menu.fullPath))
                ? this.$t(slashToHump(menu.fullPath))
                : menu.meta.title,
            },
          },
          [
            this.renderIcon(h, menu.meta.icon),
            // h('span', this.translation(getI18nKey(menu.fullPath))?this.$t(getI18nKey(menu.fullPath)):[menu.meta.title])
            h(
              "span",
              this.$te(slashToHump(menu.fullPath))
                ? this.$t(slashToHump(menu.fullPath))
                : [menu.meta.title]
            ),
          ]
        ),
      ];
      const itemArr = [];
      const pIndex_ = pIndex + "_" + index;
      if (!menu.hideChildrenInMenu) {
        menu.children.forEach(function(item, i) {
          itemArr.push(this2_.renderItem(h, item, pIndex_, i));
        });
      }
      return h(
        SubMenu,
        {
          key: menu.menuCode,
        },
        subItem.concat(itemArr)
      );
    },
    renderItem: function(h, menu, pIndex, index) {
      if (!menu.hidden) {
        return menu.children && !menu.hideChildrenInMenu
          ? this.renderSubMenu(h, menu, pIndex, index)
          : this.renderMenuItem(h, menu, pIndex, index);
      }
    },
    renderMenu: function(h, menuTree) {
      const this2_ = this;
      const menuArr = [];
      menuTree.forEach(function(menu, i) {
        if (!menu.hidden) {
          menuArr.push(this2_.renderItem(h, menu, "0", i));
        }
      });
      return menuArr;
    },
    onOpenChange(openKeys) {
      const latestOpenKey = openKeys.find(
        (key) => !this.sOpenKeys.includes(key)
      );
      if (!this.rootSubmenuKeys.includes(latestOpenKey)) {
        this.sOpenKeys = openKeys;
      } else {
        this.sOpenKeys = latestOpenKey ? [latestOpenKey] : [];
      }
    },
    updateMenu() {
      const routes = this.$route.matched.concat();
      if (routes.length >= 4 && this.$route.meta.hidden) {
        routes.pop();
        this.selectedKeys = [routes[2].meta.menuCode];
      } else {
        this.selectedKeys = [routes.pop().meta.menuCode];
      }
      this.selectedKeys = this.selectedKeys.filter((v) => v);

      let openKeys = [];
      if (this.mode === "inline") {
        routes.forEach((item) => {
          if (
            flatTreeData(this.menu ?? [], "children").some(
              (v) => v.menuCode == item.meta.menuCode
            ) &&
            item.meta &&
            item.meta.menuCode
          ) {
            openKeys.push(item.meta.menuCode);
          }
        });
      }
      //------如果是系统门户 就不展开父级菜单 2024-07-15
      if (this.$route.path == "/system/portal/index") {
        openKeys = [];
      }
      //------------------------------------
      this.collapsed
        ? (this.cachedOpenKeys = openKeys)
        : (this.sOpenKeys = openKeys);
    },
    //
    autoRouterClick(menu) {
      let { menuCode } = menu;
      let projectName = "projectName";
      if (window.blackHoleMicroApp) {
        let { blackHoleMicroApp } = window;
        let { unmount } = blackHoleMicroApp;
        //卸载
        unmount();
        //监听卸载完成
        blackHoleMicroApp.unmountPromise.then((res) => {
          this.routerLink(menuCode, projectName);
        });
      } else {
        this.routerLink(menuCode, projectName);
      }
    },

    routerLink(menuCode, projectName) {
      switch (menuCode) {
        //模型数据管理
        case `dataManage`:
          this.$router.push({
            path: `/singleProject/dataManage/$$INIT/${projectName}?dataType=Bim`,
          });
          break;

        //场景管理
        case `sceneManage`:
          this.$router.push({
            path: `/singleProject/sceneList/$$INIT/${projectName}?dataType=Bim`,
          });
          break;

        default:
          break;
      }
    },
  },

  render(h) {
    return h(
      Menu,
      {
        props: {
          theme: this.menuTheme,
          mode: this.$props.mode,
          openKeys: this.openKeys ? this.openKeys : this.sOpenKeys,
          selectedKeys: this.selectedKeys,
        },
        on: {
          //   openChange: this.onOpenChange,
          "update:openKeys": (val) => {
            this.sOpenKeys = val;
          },
          select: (obj) => {
            this.selectedKeys = obj.selectedKeys;
            this.$emit("select", obj);
          },
        },
      },
      this.renderMenu(h, this.menu)
    );
  },
};
